﻿using System;
using System.Xml;
using System.Xml.XPath;
using TheOutfield.UmbExt.UniversalMediaPicker.Extensions;
using TheOutfield.UmbExt.UniversalMediaPicker.Xslt;
using umbraco;

namespace TheOutfield.UmbExt.UniversalMediaPicker.Providers.Picasa
{
    public class PicasaXsltExtensions : AbstractXsltExtension
    {
        public static XPathNodeIterator GetMedia(int docTypeDefinitionId, string picasaId)
        {
            var provider = GetProvider<PicasaProvider>(docTypeDefinitionId);

            try
            {
                var meta = provider.GetMediaItemById(picasaId);
                
                var xd = new XmlDocument();
                var docNode = xmlHelper.addTextNode(xd, "File", "");

                if (meta != null)
                {
                    // Why won't this work??
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Id", meta.Id));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Name", meta.Title));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Url", meta.MetaData["PhotoUrl"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Size", meta.MetaData["Size"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Height", meta.MetaData["Height"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Width", meta.MetaData["Width"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "Created", meta.MetaData["Created"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "ThumbSmall", meta.MetaData["ThumbSmall"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "ThumbMedium", meta.MetaData["ThumbMedium"]));
                    docNode.AppendChild(xmlHelper.addTextNode(xd, "ThumbLarge", meta.MetaData["ThumbLarge"]));
                }

                xd.AppendChild(docNode);

                return xd.CreateNavigator().Select("/File");
            }
            catch (Exception e)
            {
                return e.ToXPathNodeIterator();
            }
        }
    }
}